package com.iring.service.pbx.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.iring.dao.common.DeviceDao;
import com.iring.dao.common.ProxyDao;
import com.iring.dao.common.UserDao;
import com.iring.domain.common.DeviceInfo;
import com.iring.domain.common.DeviceTrunk;
import com.iring.domain.common.ProxyInfo;
import com.iring.domain.common.User;
import com.iring.domain.pbx.task.PBXTask;
import com.iring.domain.pbx.task.ProxyTaskInfo;
import com.iring.domain.pbx.task.SyncUserTaskInfo;
import com.iring.domain.pbx.task.TrunkTaskInfo;
import com.iring.exception.ParamInvalidException;
import com.iring.service.common.DeviceService;
import com.iring.service.common.DeviceTrunkService;
import com.iring.service.common.UserService;
import com.iring.service.pbx.PbxService;
import com.iring.vo.pbx.SyncPbxInfo;


/**
 * 处理pbx定时请求
 *
 * @author wanggan
 */
@Service
public class PbxServiceImpl implements PbxService {
    private static final Logger logger = LoggerFactory.getLogger(PbxServiceImpl.class);

    @Autowired
    DeviceService deviceService;

    @Autowired
    UserService userService;

    @Autowired
    UserDao userDao;

    @Autowired
    DeviceTrunkService deviceTrunkService;

    @Autowired
    ProxyDao sipDao;

    @Autowired
    DeviceDao deviceDao;

    private static final String REQ_TRUNK_INFO = "req_trunk_info";
    private static final String REQ_SIP_PROXY_INFO = "req_sip_proxy_info";
    private static final String REQ_USER_INFO = "req_user_info";

    @Override
    public PBXTask syncTaskInfo(SyncPbxInfo syncPbxInfo) {
        String username = syncPbxInfo.getUsername();
        Boolean noUsername = StringUtils.isEmpty(username);
        if(noUsername){
            throw new ParamInvalidException("username is null");
        }

        String mac = syncPbxInfo.getMac();
        Boolean noMac = StringUtils.isEmpty(mac);
        if(noMac){
            throw new ParamInvalidException("mac is null");
        }

        User user = userService.getUserByUsername(username);
        if(null == user){
            throw new ParamInvalidException("invalid username");
        }

        DeviceInfo deviceInfo = deviceService.findByMac(mac);
        if(null == deviceInfo){
            throw new ParamInvalidException("invalid mac");
        }

        PBXTask pbxTask = new PBXTask();

        List<String> taskNames = syncPbxInfo.getTaskName();
        if(null == taskNames || taskNames.size()==0){
            //返回所有的任务
            pbxTask.setUser_info(doSyncUserInfoTask(username));
            pbxTask.setProxy_info(doProxyTask(mac));
            pbxTask.setTrunk_info(doTrunkTask(mac,username));
            return pbxTask;
        }

        for(String taskname : taskNames){
            switch (taskname){
                case REQ_USER_INFO:
                    //查询用户信息
                    pbxTask.setUser_info(doSyncUserInfoTask(username));
                    break;
                case REQ_SIP_PROXY_INFO:
                    //查询sip信息
                    pbxTask.setProxy_info(doProxyTask(mac));
                    break;
                case REQ_TRUNK_INFO:
                    //查询trunk信息
                    pbxTask.setTrunk_info(doTrunkTask(mac,username));
                    break;
                default:
                    logger.info("invalid mark");
            }
        }
        return pbxTask;
    }

    /**
     *
     * @param mac
     *          mac地址
     * @return  需要进行同步的prroxy任务
     */
    private ProxyTaskInfo doProxyTask(String mac){
        ProxyInfo proxyInfo = sipDao.findByMacAndSendStatusIsTrue(mac);
        DeviceInfo deviceInfo = deviceDao.findByMac(mac);
        if(null == proxyInfo || null == deviceInfo || deviceInfo.getDeviceDomain().trim().equals("")){
            return null;
        }
        ProxyTaskInfo sipTaskInfo = new ProxyTaskInfo();
        sipTaskInfo.setDeviceDomain(deviceInfo.getDeviceDomain());
        sipTaskInfo.setProxyPassword(proxyInfo.getProxyPassword());
        sipTaskInfo.setProxyPort(proxyInfo.getProxyPort());
        sipTaskInfo.setProxyUsername(proxyInfo.getProxyUsername());
        sipTaskInfo.setRealm(proxyInfo.getProxyRealm());
        return sipTaskInfo;
    }

    private TrunkTaskInfo doTrunkTask(String mac, String username){
        DeviceTrunk deviceTrunk = deviceTrunkService.findByMacAndUsername(mac, username);
        if(null == deviceTrunk){
            return null;
        }
        TrunkTaskInfo trunkTaskInfo = new TrunkTaskInfo();
        trunkTaskInfo.setTrunk_number(deviceTrunk.getIringnumber());
        trunkTaskInfo.setTrunk_password(deviceTrunk.getIringpassword());
        return trunkTaskInfo;
    }

    /**
     * 查询同步用户信息的任务
     *
     * @param username
     *          用户的信息
     * @return  同步用户信息的参数
     */
    private SyncUserTaskInfo doSyncUserInfoTask(String username){
        User user = userService.getUserByUsername(username);
        //如果密码修改过,则进行返回修改
        if(user.getIsChangePassword()) {
            SyncUserTaskInfo syncUserTaskInfo = new SyncUserTaskInfo();
            syncUserTaskInfo.setUsername(user.getUsername());
            syncUserTaskInfo.setPassword(user.getPassword());

            user.setIsChangePassword(false);
            user = userDao.save(user);
            logger.info("pbx client sync userinfo success={}",user);
            return syncUserTaskInfo;
        }
        return null;
    }
}

